const fs = require("node:fs");
const record = require("node-record-lpcm16");
const vosk = require("vosk");
const { fqueryByAI } = require('../controllers/aiQueryController');
const { say } = require('./speech');
const { countTime } = require('./countTime');
// 设置模型路径
const MODEL_PATH = "./public/vosk-model-cn-0.22"; // 替换为你的模型路径
const SAMPLE_RATE = 16000;

// 全局变量
let model = null;
let recognizer = null;
let mic = null;
let isRecording = false;
let isProcessing = false;
let stime = 0
let etime = 0
// 初始化 Vosk 模型
function initializeModel() {
    if (!fs.existsSync(MODEL_PATH)) {
        console.error("Model path does not exist.");
        return false;
    }
    vosk.setLogLevel(0);
    model = new vosk.Model(MODEL_PATH);
    recognizer = new vosk.Recognizer({
        model: model,
        sampleRate: SAMPLE_RATE,
    });
    return true;
}

// 开始录音函数
function startRecording(options = {}) {
    if (isRecording) {
        console.log("Microphone is already recording.");
        return;
    }

    // 确保模型已初始化
    if (!model || !recognizer) {
        const initSuccess = initializeModel();
        if (!initSuccess) {
            return;
        }
    }

    // 合并默认选项和用户提供的选项
    const recordingOptions = {
        sampleRateHertz: SAMPLE_RATE,
        threshold: 0,
        verbose: false,
        recordProgram: "sox", // 或 "arecord" 根据操作系统选择
        ...options
    };

    mic = record.record(recordingOptions);
    isRecording = true;

    // 设置音频流事件处理
    mic.stream().on("data", (data) => {
        if (isProcessing) {
            return;
        }

        if (recognizer.acceptWaveform(data)) {
            const result = recognizer.result();
            if (result.text && result.text.trim()) {
                isProcessing = true;
                console.log('识别结果:', result.text);
                // 处理识别结果
                stime = Date.now()
                processRecognitionResult(result.text)
                    .then((res) => {
                        etime = Date.now()
                        // 5. 用 duration 处理差值，并格式化为 HH:mm:ss
                        const timeDiff = countTime(stime, etime)
                        console.log('耗时:', timeDiff)
                        stopRecording();
                        say.speak(res)
                    })
                    .catch(err => {
                        console.error('处理错误:', err);
                        say.speak(err)

                    }).finally(() => {
                        isProcessing = false;
                        stopRecording()
                    });

            }
        } else {
            const partialResult = recognizer.partialResult();
            console.log('listening:', partialResult.partial);
            if (options.onPartialResult && typeof options.onPartialResult === 'function') {
                options.onPartialResult(partialResult.partial);
            }
        }
    });

    mic.stream().on("error", (err) => {
        console.error("Error in Input Stream: " + err);
        if (options.onError && typeof options.onError === 'function') {
            options.onError(err);
        }
    });

    mic.stream().on("startComplete", () => {
        console.log("Microphone started.");
        if (options.onStart && typeof options.onStart === 'function') {
            options.onStart();
        }
    });

    mic.stream().on("stopComplete", () => {
        console.log("Microphone stopped.");
        if (options.onStop && typeof options.onStop === 'function') {
            options.onStop();
        }
    });
    return mic;
}

// 结束录音函数
function stopRecording() {
    if (!isRecording || !mic) {
        console.log("Microphone is not recording.");
        return;
    }
    mic.stop();
    isRecording = false;
    mic = null;
    cleanup();
}

// 处理识别结果
function processRecognitionResult(text) {
    return new Promise(async (resolve, reject) => {
        try {
            const result = await fqueryByAI({
                request: {
                    body: {
                        question: text
                    }
                }
            });
            console.log('AI 处理结果:', result);
            resolve(result);
        } catch (error) {
            reject(error)
        }
    })

}

// 清理资源
function cleanup() {
    if (recognizer) {
        recognizer.free();
        recognizer = null;
    }
    if (model) {
        model.free();
        model = null;
    }
    if (mic) {
        mic.stop();
        mic = null;
        isRecording = false;
    }
}

// 导出公共接口
module.exports = {
    startRecording,
    stopRecording,
};
